// pages/ktv/pay/index.js
var app = getApp();
var interval_type = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carArray:[],
    totalPrice:0,
    totalCount:0,
    note:'',
    client_name: wx.getStorageSync('client_name'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(wx.getStorageSync("open_id"));
    console.log('opid');
    // var carArray = wx.getStorageSync('carArray');
    wx.login({
      success: function (res_code) {
        console.log(res_code);
        wx.request({
          
          url: app.globalData.erpUrl + '/web/get_wx_open_id',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: {
            code: res_code.code,
          },
          success: function (res) {
            wx.setStorageSync("open_id", res.data.openid)
            wx.hideLoading()
          }
        })
      }
    }) 
    //计划任务
    var that = this;
    that.get_table_order();
    var interval = setInterval(function () {
      if (interval_type) {
        clearInterval(interval);
      }
      that.get_table_order();
    }, 5000);

    //this.calTotalPrice();
  },

  //轮询查询该接口数据
  get_table_order: function () {
    var that = this;
    var order_id = wx.getStorageSync("order_id");
    var client = wx.getStorageSync('client');
    wx.request({
      url: app.globalData.erpUrl + '/web/hongbao/beverage/get_table_order',
      header: {
        'Content-Type': 'json'
      },
      data: {
        client: client,
        table_id: wx.getStorageSync('table_id'),
        order_id: wx.getStorageSync("order_id"),
      },
      success: function (res) {
        if (res.data.code == 200) {
          var carArray = res.data.info.order_line;
          var totalPrice = res.data.info.amount_total;
          var totalCount = res.data.info.total_num;
          that.setData({
            carArray: carArray,
            totalPrice: totalPrice,
            totalCount: totalCount,
          })
        } else if (res.data.code == 400) {
          interval_type = true;
          //删除缓存
          wx.removeStorageSync('order_id');
          wx.reLaunch({
            url: '/pages/ktv/order/index'
          })
        } else {
          //轮询出现问题销毁订单ID
          wx.removeStorageSync('order_id');
        }
      }
    })

  },


  //计算总价
  calTotalPrice: function () {
    var carArray = this.data.carArray;
    var totalPrice = 0;
    var totalCount = 0;
    for (var i = 0; i < carArray.length; i++) {
      totalPrice += carArray[i].price * carArray[i].num;
      totalCount += carArray[i].num
    }
    totalPrice = totalPrice.toFixed(2);
    this.setData({
      totalPrice: totalPrice,
      totalCount: totalCount,
    });
  },

  note: function (e){
    this.setData({
      note: e.detail.value
    })
  },

  getPay:function(){
    var that = this;
    wx.request({
      url: app.globalData.erpUrl + '/web/hongbao/beverage/get_pay_wx',
        header: {
          'Content-Type': 'json'
        },
        data: {
          client: wx.getStorageSync('client'),
          table_id: wx.getStorageSync('table_id'),
          order_id: wx.getStorageSync("order_id"),
          open_id: wx.getStorageSync("open_id"),
          note:that.data.note
        },
        success: function (res) {
          if (res.data.code == -1) {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          } else if (res.data.code == 500){
            wx.showModal({
              content: res.data.msg,
            })
          } else {
            console.log("订单支付")
            wx.requestPayment({
              'timeStamp': res.data.data.timeStamp,
              'nonceStr': res.data.data.nonceStr,
              'package': "prepay_id=" + res.data.data.prepayId,
              'signType': 'MD5',
              'paySign': res.data.data.sign,
              'success': function (res) {
                console.log(res);
                console.log(that.data.title);
                //删除缓存
                wx.removeStorageSync('order_id');
                console.log('执行加载跳转');
                //定时执行一次
                wx.showToast({
                  title: '正在支付',
                  icon: 'loading'
                })
                var interval_type =  setTimeout(function () {
                  interval_type = true;
                  wx.reLaunch({
                    url: '/pages/ktv/order/index'
                  })
                }, 2000);
                return;
              },
              'fail': function (res) {
                console.log(res);
                console.log('取消支付');
                //订单支付取消修改状态
                wx.request({
                  url: app.globalData.erpUrl + '/web/hongbao/beverage/fail_pay_wx',
                  header: {
                    'Content-Type': 'json'
                  },
                  data: {
                    client: wx.getStorageSync('client'),
                    order_id: wx.getStorageSync("order_id"),
                  },
                  success: function (res) {

                  }
                })
              }
            })
          }
        }
      })
  },


  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //检测当前状态
    var scene = app.globalData.scene;
    var d1 = wx.getStorageSync('time');
    var d2 = new Date();
    var client = wx.getStorageSync('client');
    console.log(scene);
    console.log('支付列表场景值');
    if (scene == 1089){
      console.log('支付列表跳转');
      wx.redirectTo({
        url: '/pages/ktv/code/index'
      })
    }
    // if (scene == 1089 || scene == 1001) {
    //   wx.request({
    //     url: 'https://' + client + '.zntech-china.com/web/hongbao/beverage/order_finish',
    //     header: {
    //       'Content-Type': 'json'
    //     },
    //     data: {
    //       client: client,
    //       table_id: wx.getStorageSync('table_id'),
    //       phone: wx.getStorageSync('phone'),
    //     },
    //     success: function (res) {
    //       if (res.data.code == 200) {
    //         var info = res.data.info;
    //         if (info.finish == 0) {
    //           if (d1 != '') {
    //             var int = parseInt(d2 - d1) / 1000 / 60 / 60;
    //             if (int > 2) {
    //               wx.reLaunch({
    //                 url: '/pages/ktv/code/index'
    //               })
    //             }
    //           } else {
    //             wx.reLaunch({
    //               url: '/pages/ktv/code/index'
    //             })
    //           }
    //         }
    //       }
    //     }
    //   })
    // }
    //  else {
    //   if (d1 != '') {
    //     var int = parseInt(d2 - d1) / 1000 / 60 / 60;
    //     if (int > 2) {
    //       wx.reLaunch({
    //         url: '/pages/ktv/code/index'
    //       })
    //     }
    //   } else {
    //     wx.reLaunch({
    //       url: '/pages/ktv/code/index'
    //     })
    //   }
    // }
    },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
})